package com.epoint.mobileoa.tools;

import java.util.List;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import com.epoint.mobileoa.service.MainService;

/**
 * @author liyc
 * @time 2012-8-10 下午3:20:02
 * @annotation 后台服务工具类
 */
public class BackServiceUtil {

	/**
	 * 判断一个service有无开启
	 * @param mContext 上下文
	 * @param className Service类名，包括包名
	 * @return 返回结果
	 */
	public static boolean isServiceRunning(Context mContext,String className) { 
		boolean isRunning = false; 
		ActivityManager activityManager = (ActivityManager) 
				mContext.getSystemService(Context.ACTIVITY_SERVICE);  
		List<ActivityManager.RunningServiceInfo> serviceList  
		= activityManager.getRunningServices(100);
		if (!(serviceList.size()>0)) { 
			return false; 
		} 
		for (int i=0; i<serviceList.size(); i++) { 
			if (serviceList.get(i).service.getClassName().equals(className) == true) { 
				isRunning = true; 
				break; 
			} 
		} 
		return isRunning; 
	}

	/**
	 * 开启一个service
	 * @param con 上下文
	 * @param serviceName service名称
	 * @return 1开启，0未执行打开操作
	 */
	public static int startService(Context con,String serviceName){
		if(!isServiceRunning(con, serviceName)){
			Intent mainService = new Intent(serviceName);
			con.startService(mainService);
			return 1;
		}
		return 0;
	}
	
	/**
	 * 开启MainService服务
	 * @param con 上下文
	 */
	public static void startMainService(Context con){
		startService(con,MainService.Name);
	}
	
	/**
	 * 停止MainService服务
	 * @param con
	 */
	public static void stopMainService(Context con)
	{
		Intent serviceIntent = new Intent(MainService.Name);
		con.stopService(serviceIntent);
	}
}
